package com.woniu.controller;


import com.baidu.aip.contentcensor.AipContentCensor;
import com.woniu.entity.Result;
import com.woniu.util.ALiYunUploadUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.UUID;

/**
 * @Title
 * @Author 武术有栖
 * @Description:
 */
@Api("文件上传")
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AipContentCensor aipContentCensor;

    @ApiOperation("图片上传")
    @PostMapping()
    public Result upload(MultipartFile file) throws Exception {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String originalFilename = file.getOriginalFilename();
        String last = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = uuid+last;

        //图片存储地址
        String fileLocation = "https://hmmttraintest.oss-cn-shenzhen.aliyuncs.com/"+newFileName;

        JSONObject response = aipContentCensor.imageCensorUserDefined(file.getBytes(), null);
        try {
            if (response.get("conclusionType").equals(1)){
                ALiYunUploadUtils.upload(file.getBytes(), newFileName);
                redisTemplate.opsForSet().add("redis_all_upload_image", newFileName);
            }else {
                throw new RuntimeException("图片不合规");
            }
        }catch (Exception e){
            e.printStackTrace();
            return toResult(false);
        }
        return toDataResult(fileLocation);
    }
}
